import CryptoJS from 'crypto-js/crypto-js'

const KEYHEADER = 'HNAKur'
const KEY = "ZY0iRSekfGhtZ6atmSc1xMv8Zt";
//const timestamp = parseInt(new Date().getTime() / 1000)
const secretkey = KEYHEADER + KEY;
const IV = CryptoJS.enc.Utf8.parse("HNAKurZY0iRSekfG");


export function Authorization () {
  let timestamp1 = parseInt(new Date().getTime() / 1000)
  let str = timestamp1 + KEYHEADER;

  return Encrypt(str)
}

export function Encrypt (str, ivStr, keyStr) {
  let key = CryptoJS.enc.Utf8.parse(secretkey)
  let iv = IV

  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
  }
  if (ivStr) {
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }

  let srcs = CryptoJS.enc.Utf8.parse(str);
  var encrypt = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Base64.stringify(encrypt.ciphertext);
}


export function Decrypt (str, ivStr, keyStr) {
  let key = CryptoJS.enc.Utf8.parse(secretkey)
  let iv = IV

  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
  }
  if (ivStr) {
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }

  var decrypt = CryptoJS.AES.decrypt(str, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  if (keyStr && ivStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }

  let base64 = CryptoJS.enc.Base64.parse(str);
  let src = CryptoJS.enc.Base64.stringify(base64);

  var decrypt = CryptoJS.AES.decrypt(src, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });

  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}
